<!-- components/ChatList.vue -->
<template>
  <div class="chat-list">
    <div v-for="item in chatList" :key="item.roomId" class="chat-item" @click="goToChatRoom(item.roomId)">
      <img class="avatar" :src="item.chatsList[1]?.url" alt="avatar" />
      <div class="chat-info">
        <p class="username">{{ item.chatsList[1]?.user }}</p>
        <p class="message">{{ item.chatsList[item.chatsList.length - 1]?.info }}</p>
      </div>
      <span class="time">{{ item.time }}</span>
    </div>
  </div>
</template>

<script setup>
import { chatsList } from '@/utils/jia-axios'
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter();

const chatList = ref([])

// 跳转到对应的聊天房间
const goToChatRoom = (roomId) => {
  router.push({ name: 'chatroom', query: { roomId } });
}
// 初始化聊天列表
let timer = null
function getChatsList() {
  timer = setInterval(() => {
    chatsList().then(res => {
      console.log("监听到chatsList变化", res.data.list);
      chatList.value = res.data.list
    })
  }, 500)
}
getChatsList()

const ws = ref(null);           // WebSocket 实例

// 初始化 WebSocket
const initWebSocket = () => {
  ws.value = new WebSocket('ws://localhost:3300');

  ws.value.onopen = function () {
  };

  ws.value.onmessage = function (event) {
    const data = JSON.parse(event.data);
    console.log('Received message:', data.message);
  };

  ws.value.onclose = () => {
    console.log('WebSocket 连接已关闭');
  };

  ws.value.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };
};

// 初始化 WebSocket 连接
onMounted(() => {
  initWebSocket();
});

// 组件卸载时关闭 WebSocket 连接
onUnmounted(() => {
  if (ws.value) {
    ws.value.close();
  }
  clearInterval(timer);
});
</script>

<style scoped>
.chat-list {
  padding: 10px;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
  cursor: pointer;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.chat-info {
  flex: 1;
}

.username {
  font-size: 16px;
  font-weight: bold;
}

.message {
  color: #888;
  font-size: 14px;
  margin-top: 5px;
}

.time {
  font-size: 12px;
  color: #bbb;
}
</style>